package com.google.project.client.HumanResources;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;

public class HMProjectList extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided = true)
	CellTable<ProjectDTO> ctbProjectList = new CellTable<ProjectDTO>();
	@UiField DateBox fromDate;
	@UiField DateBox toDate;
	@UiField ListBox cboStatus;
	@UiField TextBox txtProjectName;
	@UiField Button searchBtn;
	@UiField SimplePager pager;
	@UiField TextBox txtPJCode;
	@UiField LayoutPanel formSearch;
	@UiField Button btnBack;

	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	private List<ProjectDTO> listProjectDTO = new ArrayList<ProjectDTO>();

	public interface Binder extends UiBinder<Widget, HMProjectList> {
	}

	public HMProjectList() {
		initWidget(binder.createAndBindUi(this));
		fromDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		toDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		fillCbStatus();
		bindData();
	}
	
	/**
	 * Fix data to cboStatus
	 */
	public void fillCbStatus() {
		cboStatus.addItem("---Tất cả---", "-1");
		cboStatus.addItem("Dự án mới", "0");
		cboStatus.addItem("Đang tiến hành", "1");
		cboStatus.addItem("Đã kết thúc", "2");
		cboStatus.setSelectedIndex(-1);
	}

	/**
	 * Fill data to ctbProjectList
	 */
	public void bindData() {
		projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

			@Override
			public void onSuccess(List<ProjectDTO> result) {
				if(result.size() == 0) {
					Window.alert("Không có dữ liệu!");
				}
				for(ProjectDTO projectDTO : result) {
					listProjectDTO.add(projectDTO);
				}
				loadData(result);
				initTable();
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình Tải thông tin!");
			}
		});
	}

	/**
	 * @param projectList
	 */
	public void loadData(List<ProjectDTO> projectList) {
		// Create a data provider.
		ListDataProvider<ProjectDTO> dataProvider = new ListDataProvider<ProjectDTO>();

		// Add the data to the data provider, which automatically pushes it to
		// the widget

		List<ProjectDTO> list = dataProvider.getList();
		for(int i = 0; i < projectList.size(); i++) {
			projectList.get(i).setIndex(i+1);
			list.add(projectList.get(i));
		}
		// SimplePager
		pager.setDisplay(ctbProjectList);
		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbProjectList);
	}
	
	//Init Cell Table
	public void initTable() {
		//STT
		TextColumn<ProjectDTO> indexColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getIndex()+"";
			}
		};
		
		// Ma du an projectCodeColumn
		Column<ProjectDTO, String> projectCodeColumn = new Column<ProjectDTO, String>(new ClickableTextCell()) {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getProjectCode();
			}
		};
		projectCodeColumn.setFieldUpdater(new FieldUpdater<ProjectDTO, String>() {
			@Override
			public void update(int index, ProjectDTO project, String value) {
				HMEntrypoint.get().HMProjectDetail(project.getProjectID());
			}
		});
		projectCodeColumn.setCellStyleNames("celltable");
		
		// Ten du an
		TextColumn<ProjectDTO> projectNameColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getProjectName();
			}
		};

		// Quan tri du an
		TextColumn<ProjectDTO> pmColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return project.getAccountName();
			}
		};

		// Ngay bat dau
		TextColumn<ProjectDTO> startDateColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return CommonFuntion.convertToDate(new Date(project
						.getStartDate()));
			}
		};

		// Ngay ket thuc
		TextColumn<ProjectDTO> dueDateColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return CommonFuntion.convertToDate(new Date(project
						.getDueDate()));
			}
		};

		// Tinh trang
		TextColumn<ProjectDTO> statusColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				int status = project.getStatus();
				String _status = "";
				if (status == 0) {
					_status += "Dự án mới";
				} else if (status == 1) {
					_status += "Đang tiến hành";
				} else if (status == 2) {
					_status += "Đã kết thúc";
				}
				return _status;
			}
		};

		ctbProjectList.setWidth("100%", true);
		ctbProjectList.setPageSize(5);
		ctbProjectList.setPageStart(0);
		ctbProjectList.setStyleName("ttable");
		
		ctbProjectList.addColumn(indexColumn, "STT");
		ctbProjectList.setColumnWidth(indexColumn, 45.0, Unit.PX);
		
		ctbProjectList.addColumn(projectCodeColumn, "Mã dự án");
		ctbProjectList.setColumnWidth(projectCodeColumn, 15.0, Unit.PCT);
		
		
		ctbProjectList.addColumn(projectNameColumn, "Tên dự án");
		ctbProjectList.setColumnWidth(projectNameColumn, 25.0, Unit.PCT);
		projectNameColumn.setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

		ctbProjectList.addColumn(pmColumn, "Quản trị dự án");
		ctbProjectList.setColumnWidth(pmColumn, 20.0, Unit.PCT);
		
		ctbProjectList.addColumn(startDateColumn, "Ngày bắt đầu");
		ctbProjectList.setColumnWidth(startDateColumn, 17.0, Unit.PCT);
		ctbProjectList.getColumn(ctbProjectList.getColumnIndex(startDateColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		
		ctbProjectList.addColumn(dueDateColumn, "Ngày kết thúc");
		ctbProjectList.setColumnWidth(dueDateColumn, 17.0, Unit.PCT);
		ctbProjectList.getColumn(ctbProjectList.getColumnIndex(dueDateColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		
		ctbProjectList.addColumn(statusColumn,"Trạng thái");
		ctbProjectList.setColumnWidth(statusColumn, 15.0, Unit.PCT);
		ctbProjectList.getColumn(ctbProjectList.getColumnIndex(statusColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
	}

	@UiHandler("searchBtn")
	void onSearchBtnClick(ClickEvent event) {
		searchFunction();
	}
	
	//Ham search
	private void searchFunction() {
		String projectCode = txtPJCode.getText().trim();
		String projectName = txtProjectName.getText().trim();
		int projectStatus = -2;
		if(cboStatus.getValue(cboStatus.getSelectedIndex()) != null) {
			projectStatus = Integer.parseInt(cboStatus.getValue(cboStatus.getSelectedIndex()));
		}
		Long _fromDate = null;
		if(fromDate.getValue() != null) {
			_fromDate = fromDate.getValue().getTime();
		}
		Long _toDate = null;
		if(toDate.getValue() != null) {
			_toDate = toDate.getValue().getTime();
		}
		Boolean condition = true;
		
		List<ProjectDTO> temple = new ArrayList<ProjectDTO>();
		for(ProjectDTO project : listProjectDTO) {
			if(projectCode != null) {
				condition = condition && (project.getProjectCode().contains(projectCode));
			}
			if(projectName != null) {
				condition = condition && (project.getProjectName().contains(projectName));
			}
			if(_fromDate != null) {
				condition = condition && (project.getStartDate() >= _fromDate);
			}
			if(_toDate != null) {
				condition = condition && (project.getDueDate() <= _toDate);
			}
			if((cboStatus.getValue(cboStatus.getSelectedIndex()) != null) && (!cboStatus.getValue(cboStatus.getSelectedIndex()).equalsIgnoreCase("-1"))) {
				condition = condition && (project.getStatus() == projectStatus);
			}
			if(condition) {
				temple.add(project);
			}
			condition = true;
		}
		if(temple != null) {
			loadData(temple);
		} else {
			Window.alert("Không tìm thấy dữ liệu");
			loadData(temple);
		}
	}
	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
//		HMEntrypoint.get().HMGeneralInfo();	//Trang thong tin tong hop
	}
}
